//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.hzero.sso.core.common;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hzero.oauth.security.config.SecurityProperties;
import org.hzero.sso.core.domain.Domain;
import org.hzero.sso.core.support.SsoContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

public class SsoAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    public SsoAuthenticationSuccessHandler() {
    }

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HttpSession session = request.getSession(false);
        Domain domain = SsoContextHolder.getDomain();
        if (session != null && session.getAttribute("SESSION_ATTRIBUTE_LOGOUT_URL") == null) {
            String logoutUrl;
            if (domain != null && (logoutUrl = domain.getSsoLogoutUrl()) != null) {
                if (logoutUrl.indexOf("?") > 0) {
                    logoutUrl = logoutUrl + "&" + "redirect_uri" + "=" + domain.getDomainUrl();
                } else {
                    logoutUrl = logoutUrl + "?" + "redirect_uri" + "=" + domain.getDomainUrl();
                }

                session.setAttribute("SESSION_ATTRIBUTE_LOGOUT_URL", logoutUrl);
            }
        }

        // 支持华为云操作 多域名单点
        if (domain != null && domain.getSsoServerUrl().startsWith(domain.getHost())) {
            Object defaultSuccessUrl = request.getSession().getAttribute("default-success-url");
            this.setDefaultTargetUrl(String.valueOf(defaultSuccessUrl));
        }

        super.onAuthenticationSuccess(request, response, authentication);
    }
}
